package cn.kicsy.www.anonymous_bbs.interceptor;

import cn.kicsy.www.anonymous_bbs.service.CcAttackDetectionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * 自动封禁IP拦截器
 * 用于监控请求并触发自动封禁
 */
@Component
public class AutoBanInterceptor implements HandlerInterceptor {
    
    private static final Logger logger = LoggerFactory.getLogger(AutoBanInterceptor.class);
    
    @Autowired
    private CcAttackDetectionService ccAttackDetectionService;
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取客户端IP地址
        String ipAddress = getClientIpAddress(request);
        
        // 记录请求并检查是否需要自动封禁
        boolean isBanned = ccAttackDetectionService.recordRequestAndCheckBan(ipAddress);
        
        // 如果IP被封禁，则返回403错误
        if (isBanned) {
            logger.warn("IP {} 尝试访问但已被封禁", ipAddress);
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.getWriter().write("您的IP地址已被封禁，请联系管理员");
            return false;
        }
        
        return true;
    }
    
    /**
     * 获取客户端IP地址
     * @param request HTTP请求
     * @return 客户端IP地址
     */
    private String getClientIpAddress(HttpServletRequest request) {
        String ipAddress = request.getHeader("X-Forwarded-For");
        
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("HTTP_CLIENT_IP");
        }
        
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }
        
        // 如果是多个IP，则取第一个
        if (ipAddress != null && ipAddress.contains(",")) {
            ipAddress = ipAddress.split(",")[0].trim();
        }
        
        return ipAddress;
    }
}